package afcp.alumni.security;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Locale;

import net.sourceforge.stripes.util.Base64;
import net.sourceforge.stripes.validation.TypeConverter;
import net.sourceforge.stripes.validation.ValidationError;
import afcp.alumni.util.Conf;

public class PasswordEncoder implements TypeConverter<String> {
	private static final String SHA1 = "SHA-1"; //$NON-NLS-1$
	
	@Override
	public String convert(String input, Class<? extends String> cls,
			Collection<ValidationError> errors) {
		return hash(input);
	}
	
	public String convert(String input){
		return hash(input);
	}

	public static String hash(String password) {
		if (password == null) {
			return null;
		}
		try {
			MessageDigest md = MessageDigest.getInstance(SHA1);
			byte[] bytes = md.digest(password.getBytes(Conf.DEFAULT_CHARSET));
			return Base64.encodeBytes(bytes);
		} catch (NoSuchAlgorithmException exc) {
			throw new IllegalArgumentException(exc);
		}
	}

    @Override
	public void setLocale(Locale locale) {
	}
}